package org.ytor.core.querygen.support;

import org.springframework.stereotype.Component;
import org.ytor.common.util.Strs;
import org.ytor.core.querygen.AbsWhere;
import org.ytor.core.querygen.token.Token;
import org.ytor.core.sqlflow.builder.support.WhereBuilder;

/**
 * created by yangtong on 2025/8/11 14:19:14
 * <br/>
 * 模糊查询，支持全模糊，左模糊，右模糊，name=*张三*
 * <br/>
 * 优先级仅次于等值查询
 */
@Component
public class LikeWhere extends AbsWhere {
    @Override
    public Boolean isMatch(Token token) {
        String v = token.getValue();
        return Strs.isNotEmpty(v) && v.startsWith("*") && v.endsWith("*");
    }

    @Override
    protected WhereBuilder positive(WhereBuilder where, Token token) {
        String col = Strs.toUnderline(token.getKey());
        String pat = token.getValue().substring(1, token.getValue().length() - 1);
        return (WhereBuilder) where.like(col, "%" + pat + "%");
    }

    @Override
    protected WhereBuilder negate(WhereBuilder where, Token token) {
        String col = Strs.toUnderline(token.getKey());
        String pat = token.getValue().substring(1, token.getValue().length() - 1);
        return (WhereBuilder) where.expr(col + " NOT LIKE ?", "%" + pat + "%");
    }

    @Override
    public int getOrder() {
        return 0;
    }

    @Override
    public WhereBuilder apply(WhereBuilder where, Token token) {
        return positiveOrNegate(where, token);
    }
}

